<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/5/30
 * Time: 16:18
 */

namespace app\zyhsapi\controller\v1;


use app\common\lib\exception\ApiException;
use app\common\service\ApplePay;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\lib\OrdersLib;
use app\zyhsapi\model\ZyhsAppVersion;
use app\zyhsapi\model\ZyhsUserAccountRecord;
use app\zyhsmarketing\lib\RyMArk;
use Exception;
use think\Log;

/**
 *  * 苹果支付结果验证
 * Class AppPayVerify
 * 官方@document https://developer.apple.com/documentation/technologies
 * 回调@document  https://developer.apple.com/documentation/appstorereceipts
 * @package app\api\controller\v9
 */
class AppPayVerify extends ZyhsAuth
{
    /**
     * @return \think\response\Json
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $param['ticket'] = input('ticket/s', '');
        $param['order_id'] = input('order_id', '');

        Log::write('苹果支付请求参数：' . var_export($param, true), 'apple_pay', true);

        $res = ApplePay::verificationTicket(ZyhsAppVersion::iosSandboxModel(), $param['ticket']);

        if ($res['status'] !== 0 || empty($res['receipt']['in_app']) || $res['receipt']['bundle_id'] !== 'com.zhunle.rtc')
        {
            return show(config('code.success'), '请求失败');
        }

        $column = array_column($res['receipt']['in_app'], 'purchase_date_ms');
        array_multisort($column, SORT_NUMERIC, SORT_DESC, $res['receipt']['in_app']);// 得到按 支付时间 排序
        $transactionId = $res['receipt']['in_app'][0]['transaction_id'];//苹果交易ID
        $productId = $res['receipt']['in_app'][0]['product_id'];//商品ID
        $purchaseDateMs = $res['receipt']['in_app'][0]['purchase_date_ms'];//支付时间
        $gid = str_replace('zyhs_apple_pay_', '', $productId);

        $num = OrdersLib::getOrderAccountType($param['order_id'])['num'];
        //准币处理
        if ($num === 7)
        {
            try
            {
                $tmp = (new ZyhsUserAccountRecord())->where('transaction_id', $transactionId)->field('id')->find();
                if ($tmp)
                {
                    return show(config('code.success'), '');
                }
                $orders = (new ZyhsUserAccountRecord())->where(['order_id' => $param['order_id']])->field('uid,order_type,total_amount,gid,status')->findOrFail()->toArray();
                if ($orders['uid'] != $this->user['id'] || $orders['status'] || $orders['gid'] != $gid)
                {
                    return show(config('code.error'), '订单不存在');
                }
                //票据标记
                OrdersLib::UpdateCoin($param['order_id'], $orders['order_type'], $orders['total_amount'], $orders['uid'], 1, 9, $transactionId);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), '订单不存在');
            }
        }
        (new RyMArk())->recharge('applepay', $param['order_id']);//热云充值打点
        ApplePay::verificationTicket(ZyhsAppVersion::iosSandboxModel(), $param['ticket'], ApplePay::$ticketPassword, true);
        return show(config('code.success'), '请求成功');
    }
}
